package com.matt.service.impl;

import com.matt.commons.exception.BusinessException;
import com.matt.controller.po.ChildMemberPo;
import com.matt.controller.po.ChildrenPO;
import com.matt.controller.po.ParentUserPO;
import com.matt.domain.Leads;
import com.matt.domain.LeadsHistory;
import com.matt.domain.LeadsUser;
import com.matt.foundation.annotation.OptsTrace;
import com.matt.foundation.constant.LeadsConstant;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.query.LeadsQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.PoiUtill;
import com.matt.foundation.vo.ChannelVo;
import com.matt.foundation.vo.LeadsVo;
import com.matt.repository.LeadsHistoryRepository;
import com.matt.repository.LeadsRepository;
import com.matt.repository.LeadsUserRepository;
import com.matt.repository.base.LeadsNativeRepository;
import com.matt.service.AnalysisService;
import com.matt.service.BudgetTempleteService;
import com.matt.service.LeadsService;
import com.matt.remoteCall.SsoCallService;
import com.matt.service.TeachCallService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.matt.foundation.constant.OperateConstant.*;


/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2018/6/13
 * *******************************
 */
@Service
@Transactional
public class LeadsServiceImpl implements LeadsService {
    @Autowired
    private LeadsRepository leadsRepository;
    @Autowired
    private SsoCallService ssoCallService;
    @Autowired
    private TeachCallService teachCallService;

    @Autowired
    private LeadsHistoryRepository leadsHistoryRepository;
    @Autowired
    private LeadsNativeRepository leadsNativeRepository;
    @Autowired
    private LeadsUserRepository leadsUserRepository;

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private BudgetTempleteService budgetTempleteService;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public Map importExcel(String ticket, MultipartFile multipartFile) throws IOException, ParseException {

        StaffDTO staff = ssoCallService.getStaffDTO(ticket);
        String staffId = staff.getId();


        List<StaffDTO> staffs = ssoCallService.getStaffDTOList(staff.getAreaId());

        Map<String, String> nameToStaffId = new HashMap();
        staffs.stream().forEach( k ->{
            nameToStaffId.put(k.getRealName(), k.getId());
        });

        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        String areaId = baseInfo.getAreaId();

        int cellNum = 11 ;//只处理前11列, 线索来源	幼儿姓名	性别	出生年月	家长姓名	关系	家长联系电话	负责人	家庭住址，乳名
//        List<ChannelVo> list = budgetTempleteService.findAll(areaId);

        Map response  =   PoiUtill.readXls(multipartFile, cellNum);
        boolean isCheck = (boolean)response.get("isCheck");
        if(!isCheck)
            throw  new BusinessException(ErrorCode.EXCEL_CHECK_ERROR,"表格校验不通过，必填项不能为空!");

        List<String> dataList = (List<String>)response.get("list");

        int fullRecordCount = dataList.size();
        int validCount = 0;
        int successCount = 0;

        List<String> skippedLeads = new ArrayList<>();

//        StringBuffer resultInfo = new StringBuffer();
//        AtomicInteger existCount = new AtomicInteger(0);
//        resultInfo.append("一共保存").append(dataList.size()).append("条线索记录");

        for(int k = 1/*跳过表头*/ ; k < dataList.size() ; k++) {
            String dataStr = dataList.get(k);

            String[] arry = dataStr.split(",");
            if (ArrayUtils.isEmpty(arry)) {
                continue;
            }

            for(int i = 0; i < arry.length ; i++){
                arry[i] = StringUtils.trim(arry[i]);
            }

            //有效行计数器
            validCount += 1;

            String dealer = arry.length > 7 ? arry[7] : null;

            Leads leads = arrayInfo2Leads(areaId, k, arry);
            String childrenName = leads.getChildName();
            String mobile = leads.getMobile();
//            String channel = leads.getChannel();
            Integer chan = leads.getChannStatus();

            String reason = null;

            if( StringUtils.isBlank(childrenName)){
                reason = "宝宝姓名为空";
            }else if (chan==null){
                reason = "线索来源为空";
            }
            else if( StringUtils.isBlank(leads.getMobile()) || !isPhoneNum(leads.getMobile())){
                reason = "电话号码为空";
            }else if( StringUtils.isBlank(dealer)){
                reason = "负责人为空";
            }else if( StringUtils.isBlank(leads.getNickName())){
                reason = "宝宝乳名为空";
            }


            if (reason != null){
                skippedLeads.add(reason + "|" + dataStr);
                continue;
            }
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndDeletedFalse(childrenName, mobile, areaId);
//            Leads exist = leadsRepository.findByMobile(leads.getIdCard());
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), areaId,leads.getNickName(),leads.getBirthday());
            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(leads.getChildName(), leads.getMobile(), areaId,leads.getNickName());
            if (exist != null) {
                skippedLeads.add("信息已注册" + "|" +dataStr);
                if (!StringUtils.equals(exist.getStaffName(),dealer)){
                    exist.setStaffName(dealer);
                    exist.setStaffId(nameToStaffId.get(dealer));
                    leadsRepository.save(exist);
                }
                continue;
            }

            LeadsUser leadsUser=leadsUserRepository.findTopByChildBigNameAndMobileAndAreaIdAndDeletedFalse(childrenName,mobile,areaId);
            if (leadsUser!=null){
                skippedLeads.add("信息已注册" + "|" +dataStr);
                Leads exist1 = leadsRepository.findById(leadsUser.getLeadsId()).get();
                if (!StringUtils.equals(exist1.getStaffName(),dealer)){
                    exist1.setStaffName(dealer);
                    exist1.setStaffId(nameToStaffId.get(dealer));
                    leadsRepository.save(exist1);
                }
                continue;
            }

            if (StringUtils.isEmpty(dealer) || nameToStaffId.get(dealer) == null) {
                leads.setStaffId(baseInfo.getId());
                leads.setStaffName(baseInfo.getRealName());
            } else {
                leads.setStaffName(dealer);
                leads.setStaffId(nameToStaffId.get(dealer));
            }


            leads.setCategory(1);
            leadsRepository.save(leads);
            leadsUser=new LeadsUser();
            leadsUser.setLeadsId(leads.getId());
            leadsUser.setUserName(leads.getName());
            leadsUser.setAddress(leads.getHomeAddress());
            leadsUser.setRelationship(leads.getRelationship());
            leadsUser.setChildBigName(leads.getChildName());
            leadsUser.setType(1);
            leadsUser.setAreaId(areaId);
            leadsUser.setRemarks(leads.getRemark());
            leadsUser.setMobile(leads.getMobile());
            leadsUserRepository.save(leadsUser);
            saveLeadsHistoryInfo(baseInfo, leads);

            if (Objects.nonNull(leads.getLastFollowRecord())){
                String remarks = leads.getLastFollowRecord();
                saveLeadsHistoryInfo_v2(baseInfo, leads,remarks);
            }
            analysisService.create(leads.getId(), leads.getCategory(), leads.getChannelId(), leads.getAreaId(),
                    leads.getStaffId(), leads.getCreated());

            //总计数器
            successCount += 1;
        }

        Map result = new HashMap();
        result.put("skippedLeads", skippedLeads);
        result.put("fullRecordCount", fullRecordCount);
        result.put("validCount", validCount);
        result.put("successCount", successCount);

        return result;
    }

    public static boolean isPhoneNum(final String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[0-9]{7,}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    public Integer convertChannelStatus(String channStatus) {
        // 处理空值（若未trim，这里再做一次安全处理）
        if (StringUtils.isEmpty(channStatus)) {
            return 1; // 空值返回默认值1
        }

        // 建立字符串与整数的映射关系（严格匹配中文名称）
        switch (channStatus) {
            case "美团":
                return 1;
            case "转介绍":
                return 2;
            case "大众点评":
                return 3;
            case "抖音":
                return 4;
            default:
                // 不匹配的字符串返回默认值1（可根据需求调整，如抛异常）
                return 1;
        }
    }

    public Integer convertChannelrankp(String rankp) {
        // 处理空值（若未trim，这里再做一次安全处理）
        if (StringUtils.isEmpty(rankp)) {
            return 0; // 空值返回默认值1
        }

        // 建立字符串与整数的映射关系（严格匹配中文名称）
        switch (rankp) {
            case "重点客户":
                return 0;
            case "普通客户":
                return 1;
            case "非优先客户":
                return 2;
            case "意愿不强":
                return 3;
            default:
                // 不匹配的字符串返回默认值1（可根据需求调整，如抛异常）
                return 0;
        }
    }
    private Leads arrayInfo2Leads(String areaId , int index, String[] array){

//        String channel = StringUtils.trim(array[0]) ;
        String channStatus = StringUtils.trim(array[0]) ;
        String channelStatus = StringUtils.trim(array[0]) ;
        String childrenName = StringUtils.trim(array[1]);
        String sex = array[2];
        int gender = "男".equals(sex) ? 1 : 0;
        String birthdayStr = array[3];
        String lastFollowRecord = array.length > 8 ? array[8] : null;
        Date birthday = null;

        if (!StringUtils.isBlank(birthdayStr)){
//            throw new BusinessException(ErrorCode.EXCEL_CHECK_ERROR, String.format("第%d行线索 生日 字段为空", index, birthdayStr));
            try {
                birthday = DateTime.parse(birthdayStr, DateTimeFormat.forPattern("yyyy-MM-dd")).toDate();
            }catch (Exception e){
                e.printStackTrace();
                throw new BusinessException(ErrorCode.EXCEL_CHECK_ERROR, String.format("第%d行线索 生日 字段（%s）处理出错，正确示例: 2015-07-01", index, birthdayStr));
            }
        }

        String name = array[4];
        String relationship = StringUtils.trim(array[5]);
        String mobile = StringUtils.trim(array[6]);
        String homeAddress = "";
//        array.length > 8 ? array[8] : null;

        Leads leads = new Leads();
        leads.setAreaId(areaId);
        leads.setChildName(childrenName);
        leads.setZhwysStatus("0");
        leads.setClientStatus(1);
        leads.setTypeStatus(1);
//        leads.setLastFollowRecord(lastFollowRecord);
        leads.setGender(gender);
        leads.setRankp(gender);
        leads.setBirthday(birthday);
        leads.setMobile(mobile);
        leads.setChannel("1");
        leads.setChannelId("aa11651ea62f43e5a1e8d5421c92339b");
        leads.setChannStatus(convertChannelStatus(channStatus));
        leads.setChannelStatus(convertChannelStatus(channelStatus));
        leads.setName(name);
        leads.setIdCard(StringUtils.trim(array[8]));
        leads.setRankp(convertChannelrankp(array[9]));
        leads.setNickName(StringUtils.trim(array[10]));
        leads.setRelationship(relationship);
        leads.setHomeAddress(homeAddress);

        return leads;
    }

    /**
     * 保存销售动态
     * @param baseInfo
     * @param leads
     */
    private void saveLeadsHistoryInfo(StaffDTO baseInfo, Leads leads) {

        if (StringUtils.isNotEmpty(leads.getId())) {
            LeadsHistory leadsHistory = new LeadsHistory();

            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 从“Excel批量导入”创建了本条数据");
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(baseInfo.getId());
            leadsHistory.setStaffName(baseInfo.getRealName());
            leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());

            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }
    }


    /**
     * 保存销售动态
     * @param baseInfo
     * @param leads
     */
    private void saveLeadsHistoryInfo_v2(StaffDTO baseInfo, Leads leads,String content) {

        if (StringUtils.isNotEmpty(leads.getId())) {
            LeadsHistory leadsHistory = new LeadsHistory();

            Date date = new Date();
            date.setTime(date.getTime()+1000);
            leadsHistory.setCreated(date);
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent(content);
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(baseInfo.getId());
            leadsHistory.setStaffName(baseInfo.getRealName());
            leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());

            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }
    }

    @Override
    public Leads saveToNoneOne(Leads leads, String source){
//        if (StringUtils.isNotBlank(leads.getId())) {
//            throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "指定id的线索不存在");
//        }

        //新增用户，检查线索是否存在
//        Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndDeletedFalse(leads.getName(), leads.getMobile(), leads.getAreaId());
//        Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), leads.getAreaId(),leads.getNickName(),leads.getBirthday());
        Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(leads.getChildName(), leads.getMobile(), leads.getAreaId(),leads.getNickName());
//        Leads exist = leadsRepository.findByMobile(leads.getIdCard());
        if(exist != null){
            //跟进一下，刷新时间

            return exist;
        }

        //创建新的线索总是指定到当前用户
        leads.setStatus(LeadsConstant.Status.NON_HANDLE.codeOf());

        //状态
        leads.setChangeStatus(LeadsConstant.ChangeStatus.NON_TRANSFER.codeOf());
        leads.setChangeStatusVal(LeadsConstant.ChangeStatus.NON_TRANSFER.valueOf());

        //添加销售动态
        LeadsHistory leadsHistory = new LeadsHistory();
        if (StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent(source);
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);

            leadsHistory.setAreaId(leads.getAreaId());
        }

        leadsRepository.save(leads);

        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }

        //添加主动例子统计数据
        analysisService.create(leads.getId(), leads.getCategory(), leads.getChannelId(), leads.getAreaId(), leads.getStaffId(), leads.getCreated());

        return leads;
    }

    @OptsTrace(code = "10001")
    @Override
    public LeadsVo save(Leads leads, String ticket) {
        StaffDTO modifyStaff=new StaffDTO();
        String id = "";
        String realName = "";
        String areaId = "";
        if (ticket!=null){
            modifyStaff = ssoCallService.getStaffDTO(ticket);
            areaId=modifyStaff.getAreaId();
            id = modifyStaff.getId();
            realName = modifyStaff.getRealName();
        }else {
            areaId=leads.getAreaId();

        }
        System.out.println("areaId===============:"+areaId);
        System.out.println("areaId1===============:"+leads.getAreaId());
        System.out.println("id===============:"+id);
        System.out.println("realName===============:"+realName);
        System.out.println("Birthday===============:"+leads.getBirthday());
        leads.setAreaId(areaId);
        if(Objects.isNull(leads.getGender())){
            leads.setGender(2);
        }
        if (StringUtils.isBlank(leads.getId())) {
            // 1. 清洗字段（去空格、空值处理）
            String childName = StringUtils.trimToEmpty(leads.getChildName());
            String mobile = StringUtils.trimToEmpty(leads.getMobile());
            String nickName = StringUtils.trimToEmpty(leads.getNickName());
            String checkAreaId = areaId;

            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(
                    childName, mobile, checkAreaId, nickName
            );
            //新增用户，检查线索是否存在
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName(),leads.getBirthday());
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(
//                    leads.getName(), leads.getMobile(), areaId, leads.getNickName() // 用areaId变量，而非modifyStaff.getAreaId()
//            );//            Leads exist = leadsRepository.findByMobile(leads.getIdCard());
            if(exist != null){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
            }
//            ParentUser user=ssoCallService.getUserByMobile(leads.getMobile());
            //创建新的线索总是指定到当前用户

            System.out.println("当前用户id===============:"+id);
            leads.setStaffId(id);
            leads.setStaffName(realName);


            leads.setStatus(LeadsConstant.Status.NON_HANDLE.codeOf());
        } else {
            //修改用户
            Leads oldLeads = leadsRepository.findById(leads.getId()).get();

            if ( oldLeads == null || (oldLeads != null && !oldLeads.getAreaId().equals(leads.getAreaId()))){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
            }

//            if (StringUtils.isNotBlank(leads.getMobile())){
//                if(!leads.getMobile().equals(oldLeads.getMobile())){
//                    Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId());
////                    Leads exist = leadsRepository.findByMobile(leads.getMobile());
//                    if(exist != null){
//                        throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
//                    }
//                }
//            }

            //
//            BeanUtils.copyProperties();
//            leads.setStatus(oldLeads.getStatus());
//            leads.setCreated(oldLeads.getCreated());
//            leads.setAreaId(oldLeads.getAreaId());
//            leads.setStaffId(oldLeads.getStaffId());
//            leads.setStaffName(oldLeads.getStaffName());
//            leads.setLastFollowRecord(oldLeads.getLastFollowRecord());
//            leads.setLastFollowTime(oldLeads.getLastFollowTime());
        }

        //最后修改时间
        Date now = new Date();
        leads.setLastModified(now);
        leads.setLastModifiedId(id);


        //状态
        leads.setChangeStatus(LeadsConstant.ChangeStatus.NON_TRANSFER.codeOf());
        leads.setChangeStatusVal(LeadsConstant.ChangeStatus.NON_TRANSFER.valueOf());
        leads.setClientStatus(leads.getClientStatus());
        leads.setChannStatus(leads.getClientStatus());
        //添加销售动态
        LeadsHistory leadsHistory = new LeadsHistory();
        if (StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 创建了本条数据");
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(id);
            leadsHistory.setStaffName(realName);
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }

        leadsRepository.save(leads);

        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }
        LeadsUser leadsUser=leadsUserRepository.findByLeadsIdAndMobile(leads.getId(),leads.getMobile());

        if (leadsUser==null){
            leadsUser=new LeadsUser();
            leadsUser.setLeadsId(leads.getId());
            leadsUser.setUserName(leads.getName());
            leadsUser.setAddress(leads.getHomeAddress());
            leadsUser.setRelationship(leads.getRelationship());
            leadsUser.setChildBigName(leads.getChildName());
            leadsUser.setType(1);
            leadsUser.setAreaId(areaId);
            leadsUser.setRemarks(leads.getRemark());
            leadsUser.setMobile(leads.getMobile());
            leadsUserRepository.save(leadsUser);

        }else {
            leadsUser.setUserName(leads.getName());
            leadsUser.setAddress(leads.getHomeAddress());
            leadsUser.setRelationship(leads.getRelationship());
            leadsUser.setChildBigName(leads.getChildName());
            leadsUser.setRemarks(leads.getRemark());
            leadsUser.setMobile(leads.getMobile());
            leadsUserRepository.save(leadsUser);
        }


        //添加主动例子统计数据
        analysisService.create(leads.getId(), leads.getCategory(), leads.getChannelId(), leads.getAreaId(), leads.getStaffId(), leads.getCreated());

        LeadsVo leadsVo = new LeadsVo();
        BeanUtils.copyProperties(leads, leadsVo);
        leadsVo.setBirthday(leads.getBirthday() == null ? null : leads.getBirthday().getTime());
        leadsVo.setLastFollowTime(leads.getLastFollowTime() == null ? null : leads.getLastFollowTime().getTime());
        leadsVo.setLastModified(leads.getLastModified() == null ? null : leads.getLastModified().getTime());
        return leadsVo;
    }




    @OptsTrace(code = "10001")
    @Override
    public LeadsVo save1(Leads leads, String ticket) {
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        leads.setAreaId(modifyStaff.getAreaId());
        if(Objects.isNull(leads.getGender())){
            leads.setGender(2);
        }
        if (StringUtils.isBlank(leads.getId())) {
            //新增用户，检查线索是否存在
            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName());
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName(),leads.getBirthday());
//            Leads exist = leadsRepository.findByMobile(leads.getMobile());
            if(exist != null){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
            }
//            ParentUser user=ssoCallService.getUserByMobile(leads.getMobile());
            //创建新的线索总是指定到当前用户
            leads.setStaffId(modifyStaff.getId());
            leads.setStaffName(modifyStaff.getRealName());

            leads.setStatus(LeadsConstant.Status.NON_HANDLE.codeOf());
        } else {
            //修改用户
            Leads oldLeads = leadsRepository.getOne(leads.getId());

            if ( oldLeads == null || (oldLeads != null && !oldLeads.getAreaId().equals(leads.getAreaId()))){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
            }

            if (StringUtils.isNotBlank(leads.getMobile())){
                if(!leads.getMobile().equals(oldLeads.getMobile())){
                    Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(leads.getChildName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName());
//                    Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName(),leads.getBirthday());
//                    Leads exist = leadsRepository.findByMobile(leads.getMobile());
                    if(exist != null){
                        throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
                    }
                }
            }

            //
//            leads.setStatus(oldLeads.getStatus());
//            leads.setCreated(oldLeads.getCreated());
//            leads.setAreaId(oldLeads.getAreaId());
//            leads.setStaffId(oldLeads.getStaffId());
//            leads.setStaffName(oldLeads.getStaffName());
//            leads.setLastFollowRecord(oldLeads.getLastFollowRecord());
//            leads.setLastFollowTime(oldLeads.getLastFollowTime());
        }

        //最后修改时间
        Date now = new Date();
        leads.setLastModified(now);
        leads.setLastModifiedId(modifyStaff.getId());

        //状态
        leads.setChangeStatus(LeadsConstant.ChangeStatus.NON_TRANSFER.codeOf());
        leads.setChangeStatusVal(LeadsConstant.ChangeStatus.NON_TRANSFER.valueOf());

        //添加销售动态
        LeadsHistory leadsHistory = new LeadsHistory();
        if (StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 创建了本条数据");
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(modifyStaff.getId());
            leadsHistory.setStaffName(modifyStaff.getRealName());
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }

        leadsRepository.save(leads);

        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }
        LeadsUser leadsUser=leadsUserRepository.findByLeadsIdAndMobile(leads.getId(),leads.getMobile());

        if (leadsUser==null){
            leadsUser=new LeadsUser();
            leadsUser.setLeadsId(leads.getId());
            leadsUser.setUserName(leads.getName());
            leadsUser.setAddress(leads.getHomeAddress());
            leadsUser.setRelationship(leads.getRelationship());
            leadsUser.setChildBigName(leads.getChildName());
            leadsUser.setType(1);
            leadsUser.setAreaId(modifyStaff.getAreaId());
            leadsUser.setRemarks(leads.getRemark());
            leadsUser.setMobile(leads.getMobile());
            leadsUserRepository.save(leadsUser);

        }


        //添加主动例子统计数据
        analysisService.create(leads.getId(), leads.getCategory(), leads.getChannelId(), leads.getAreaId(), leads.getStaffId(), leads.getCreated());

        LeadsVo leadsVo = new LeadsVo();
        BeanUtils.copyProperties(leads, leadsVo);
        leadsVo.setBirthday(leads.getBirthday() == null ? null : leads.getBirthday().getTime());
        leadsVo.setLastFollowTime(leads.getLastFollowTime() == null ? null : leads.getLastFollowTime().getTime());
        leadsVo.setLastModified(leads.getLastModified() == null ? null : leads.getLastModified().getTime());
        return leadsVo;
    }



    @Override
    public Leads updateById(Leads leads,String ticket){
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);
        //修改用户
        Leads oldLeads = leadsRepository.getOne(leads.getId());

        if ( oldLeads == null || (oldLeads != null && !oldLeads.getAreaId().equals(leads.getAreaId()))){
            throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        if (StringUtils.isNotBlank(leads.getMobile())){
            if(!leads.getMobile().equals(oldLeads.getMobile())){
                Leads exist = leadsRepository.findByMobileAreaId(leads.getMobile(), leads.getAreaId());
                if(exist != null){
                    throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
                }
            }
        }

        //最后修改时间
        Date now = new Date();
        leads.setId(leads.getId());
        leads.setAreaId(oldLeads.getAreaId());
        leads.setLastModified(now);
        leads.setLastModifiedId(modifyStaff.getId());
        return leadsRepository.save(leads);
    }

    @Override
    public LeadsVo save(Leads leads, String areaId, String ticket) {
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        leads.setAreaId(areaId);
        if(Objects.isNull(leads.getGender())){
            leads.setGender(2);
        }
        if (StringUtils.isBlank(leads.getId())) {
            //新增用户，检查线索是否存在
            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndDeletedFalse(leads.getChildName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName());
//            Leads exist = leadsRepository.findTopByChildNameAndMobileAndAreaIdAndNickNameAndBirthdayAndDeletedFalse(leads.getName(), leads.getMobile(), modifyStaff.getAreaId(),leads.getNickName(),leads.getBirthday());
            if(exist != null){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
            }

            //创建新的线索总是指定到当前用户
            leads.setStaffId(modifyStaff.getId());
            leads.setStaffName(modifyStaff.getRealName());

            leads.setStatus(LeadsConstant.Status.NON_HANDLE.codeOf());
        } else {
            //修改用户
            Leads oldLeads = leadsRepository.getOne(leads.getId());

            if ( oldLeads == null || (oldLeads != null && !oldLeads.getAreaId().equals(leads.getAreaId()))){
                throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
            }

            if (StringUtils.isNotBlank(leads.getMobile())){
                if(!leads.getMobile().equals(oldLeads.getMobile())){
                    Leads exist = leadsRepository.findByMobileAreaId(leads.getMobile(), areaId);
                    if(exist != null){
                        throw new BusinessException(ErrorCode.LEADS_NOT_EXIST, "已经存在同用户线索");
                    }
                }
            }

            //
            leads.setStatus(oldLeads.getStatus());
            leads.setCreated(oldLeads.getCreated());
            leads.setAreaId(oldLeads.getAreaId());
            leads.setStaffId(oldLeads.getStaffId());
            leads.setStaffName(oldLeads.getStaffName());
            leads.setLastFollowRecord(oldLeads.getLastFollowRecord());
            leads.setLastFollowTime(oldLeads.getLastFollowTime());
        }

        //最后修改时间
        Date now = new Date();
        leads.setLastModified(now);
        leads.setLastModifiedId(modifyStaff.getId());

        //状态
        leads.setChangeStatus(LeadsConstant.ChangeStatus.NON_TRANSFER.codeOf());
        leads.setChangeStatusVal(LeadsConstant.ChangeStatus.NON_TRANSFER.valueOf());

        //添加销售动态
        LeadsHistory leadsHistory = new LeadsHistory();
        if (StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 创建了本条数据");
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(modifyStaff.getId());
            leadsHistory.setStaffName(modifyStaff.getRealName());
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }

        leadsRepository.save(leads);

        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }

        //添加主动例子统计数据
        analysisService.create(leads.getId(), leads.getCategory(), leads.getChannelId(), areaId, leads.getStaffId(), leads.getCreated());

        LeadsVo leadsVo = new LeadsVo();
        BeanUtils.copyProperties(leads, leadsVo);
        leadsVo.setBirthday(leads.getBirthday() == null ? null : leads.getBirthday().getTime());
        leadsVo.setLastFollowTime(leads.getLastFollowTime() == null ? null : leads.getLastFollowTime().getTime());
        leadsVo.setLastModified(leads.getLastModified() == null ? null : leads.getLastModified().getTime());
        return leadsVo;
    }

    @Override
    public Leads findById(String leadsId, String areaId) {
        //查询线索
        Leads leads = leadsRepository.findByIdAndAreaId(leadsId, areaId);
        List<LeadsUser> byLeadsId = leadsUserRepository.findByLeadsIdOrderByTypeAsc(leadsId);
        leads.setList(byLeadsId);
        if(leads.getBirthday()!=null){
            LocalDate date = LocalDate.now();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = formatter.format(leads.getBirthday());
            LocalDate localDate = LocalDate.parse(formattedDate);
            long monthsBetween = ChronoUnit.MONTHS.between(localDate,date);
            leads.setMonthsDiff(String.valueOf(monthsBetween));
        }
        return leads;
    }

    @OptsTrace(code = "10002")
    @Override
    public int deleteByIdInArea(String leadsId, String ticket, String areaId) {

        Leads leads = leadsRepository.findByIdAndAreaId(leadsId, areaId);

        if(leads == null){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

//        //先删除线索对应的根据信息
//        int i = leadsHistoryRepository.deleteByLeadsId(leadsId);
//
//        //删除线索
//        leadsRepository.delete(leads);
        leads.setDeleted(true);
        leadsRepository.save(leads);

        return 1;
    }

    @Override
    public Page<Leads> findPage(LeadsQuery leadsQuery, Pageable pageable) {
        List<Leads> lists = leadsNativeRepository.findByCondition(leadsQuery);
        LocalDate date = LocalDate.now();

        if(!lists.isEmpty()){
            lists.forEach(a->{
                if(a.getBirthday()!=null){
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = formatter.format(a.getBirthday());
                    LocalDate localDate = LocalDate.parse(formattedDate);
                    long monthsBetween = ChronoUnit.MONTHS.between(localDate,date);
                    a.setMonthsDiff(String.valueOf(monthsBetween));
                    String ageStr = "0月";
                    Instant instant = a.getBirthday().toInstant();
                    ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Shanghai")); // 固定时区
                    LocalDate birthDate = zdt.toLocalDate();
                    LocalDate now = LocalDate.now(ZoneId.of("Asia/Shanghai"));
                    Period period = Period.between(birthDate, now);

                    StringBuilder ageBuilder = new StringBuilder();
                    if (period.getYears() > 0) {
                        ageBuilder.append(period.getYears()).append("年");
                    }
                    if (period.getMonths() > 0) {
                        ageBuilder.append(period.getMonths()).append("月");
                    }
                    ageStr = ageBuilder.length() > 0 ? ageBuilder.toString() : "0月";
                    a.setAge(ageStr);
                }
            });
        }
        Long count = leadsNativeRepository.countLeads(leadsQuery);
        return new PageImpl<>(lists,  PageRequest.of(leadsQuery.getPageNum(), leadsQuery.getPageSize()), count);
    }

    @OptsTrace(code = "10003")
    @Override
    public Leads updateLeadsStaffInfo(String ticket, String staffId, String staffName, String leadsId) {

        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        Leads leads = leadsRepository.findByIdAndAreaId(leadsId, modifyStaff.getAreaId());

        if(leads == null){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        StaffDTO targetUser = ssoCallService.getStaffDTO(ticket, staffId);
        if(StringUtils.isEmpty(targetUser.getAreaId()) || !targetUser.getAreaId().equals(modifyStaff.getAreaId()) ){
            throw  new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }

        leads.setStaffId(targetUser.getId());
        leads.setStaffName(targetUser.getRealName());

        return leadsRepository.save(leads);
    }

    @Override
    public Leads updateStatusById(String ticket,String zhwysStatus, String leadsId){
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        Leads leads = leadsRepository.findByIdAndAreaId(leadsId, modifyStaff.getAreaId());

        if(leads == null){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }
       if ("5".equals(zhwysStatus)) {
           leads.setStaffId("");
           leads.setStaffName("");
           leads.setSeasTime(new Date());
       }

       leads.setZhwysStatus(zhwysStatus);
       //添加销售动态
        leadsRepository.save(leads);
        LeadsHistory leadsHistory = new LeadsHistory();
        if (!StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            if (zhwysStatus.equals("5")){
                leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 投入公海");
                leadsHistory.setOperationType("ok");
            }
            if ("4".equals(zhwysStatus)){
                leadsHistory.setContent("线索已被放弃");
                leadsHistory.setOperationType(OPERATE_BREAK);
            }
            if ("1".equals(zhwysStatus)){
                leadsHistory.setContent("线索已激活");
                leadsHistory.setOperationType("ok");
            }

            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(modifyStaff.getId());
            leadsHistory.setStaffName(modifyStaff.getRealName());
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }
        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }

        return leads;
    }

    @Override
    public Object updatePennyById(String ticket, Leads leads) {
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        Leads lead = leadsRepository.findByIdAndAreaId(leads.getId(), modifyStaff.getAreaId());
        BigDecimal penny = lead.getPenny();
        BigDecimal penny1 = leads.getPenny();
        BigDecimal add = penny1.add(penny);
        lead.setPenny(add);
        lead.setRenewalMethod(leads.getRenewalMethod());
        lead.setUserId(leads.getUserId());
        lead.setUserName(leads.getUserName());
        lead.setZhwysStatus("2");

        leadsRepository.save(lead);
        //添加销售动态 follow
        LeadsHistory leadsHistory = new LeadsHistory();
        if (!StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("客户已缴纳定金，缴纳人 " +leads.getUserName()+ " 缴纳了定金 "+add);
            leadsHistory.setOperationType(OPERATE_BACK_MONEY);
            leadsHistory.setLeadsId(leads.getId());
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(modifyStaff.getId());
            leadsHistory.setStaffName(modifyStaff.getRealName());
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }
        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }

        return lead;
    }

    @Override
    @Transactional
    public Object updateStatusByLeads(String ticket, ChildMemberPo po1) {
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        Leads leads = leadsRepository.findByIdAndAreaId(po1.getLeadsId(), modifyStaff.getAreaId());

        if(leads == null){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        leads.setZhwysStatus(po1.getZhwysStatus());
        leadsRepository.save(leads);
        //如果不是创建宝宝生成的线索就需要去创建宝宝
        if (!"老师添加".equals(leads.getChannel())){
            ChildrenPO po = getChildrenPO(po1, leads, modifyStaff);
            String childId = teachCallService.addByLeads(ticket, po);

            if (StringUtils.isNotBlank(childId)){
                po1.setPoType(1);
                po1.setChildId(childId);
                po1.setAreaId(modifyStaff.getAreaId());
                po1.setStaffName(modifyStaff.getRealName());
                po1.setStaffId(modifyStaff.getId());
                ssoCallService.addChildMember(po1);
            }else {
                throw new  BusinessException(ErrorCode.LEADS_NOT_EXIST, "宝宝id不存在，需要删除数据，重新新增");
            }
        }
        //添加销售动态 follow
        LeadsHistory leadsHistory = new LeadsHistory();
        if (!StringUtils.isBlank(leads.getId())) {
            Date date = new Date();
            leadsHistory.setStaffName(leads.getStaffName());
            leadsHistory.setType("leads");
            leadsHistory.setContent("客户已成交");
            leadsHistory.setOperationType("ok");
            leadsHistory.setLeadsId(leads.getId());
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(modifyStaff.getId());
            leadsHistory.setStaffName(modifyStaff.getRealName());
            leadsHistory.setStaffHeadImgUrl(modifyStaff.getHeadImgUrl());
            leadsHistory.setAreaId(leads.getAreaId());
        }
        if ("leads".equals(leadsHistory.getType())) {
            leadsHistory.setLeadsId(leads.getId());
            leadsHistoryRepository.save(leadsHistory);
        }
        return leads;
    }

    @Override
    public List<Map<String, Object>> getAllArea() {
        List<Map<String, Object>> areaMaps = leadsRepository.getAllArea();
        // 可根据需要进一步处理Map（如类型转换、字段过滤等）
        return areaMaps;

    }

    @Override
    public Object updateLeadsStaffInfo1(String ticket, String staffId, String staffName, List<String> leadsId) {
        StaffDTO modifyStaff = ssoCallService.getStaffDTO(ticket);

        String mobile = modifyStaff.getMobile();

        List<Leads> leads= leadsRepository.findByIdAndAreaId1(leadsId, modifyStaff.getAreaId());

        if(leads == null||leads.isEmpty()){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

        StaffDTO targetUser = ssoCallService.getStaffDTO(ticket, staffId);
        if(StringUtils.isEmpty(targetUser.getAreaId()) || !targetUser.getAreaId().equals(modifyStaff.getAreaId()) ){
            throw  new BusinessException(ErrorCode.STAFF_NOT_EXIST, "员工不存在");
        }
        List<LeadsHistory> list=new ArrayList<>();
        leads.forEach(e->{
            e.setStaffId(targetUser.getId());
            e.setStaffName(targetUser.getRealName());
            leadsRepository.save(e);
            Date date = new Date();
            StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
            LeadsHistory leadsHistory = new LeadsHistory();
            leadsHistory.setType("leads");
            leadsHistory.setOperationType(OPERATE_TRANSFER);
            leadsHistory.setContent("在 "+DateUtil.dateToymd(date)+" 将本数据转移给了 \""+staffName+"\""+mobile);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setLeadsId(e.getId());
            leadsHistory.setStaffId(baseInfo.getId());
            leadsHistory.setStaffName(baseInfo.getRealName());
            leadsHistory.setStaffHeadImgUrl(baseInfo.getHeadImgUrl());
            leadsHistory.setAreaId(baseInfo.getAreaId());
            list.add(leadsHistory);
        });
        leadsHistoryRepository.saveAll(list);


        return leads;
    }

    @Override
    public Object deleteByIdInArea1(List<String> leadsId, String ticket, String areaId) {
        List<Leads> leads= leadsRepository.findByIdAndAreaId1(leadsId, areaId);

        if(leads == null||leads.isEmpty()
        ){
            throw  new BusinessException(ErrorCode.LEADS_NOT_EXIST, "线索不存在");
        }

//        //先删除线索对应的根据信息
//        int i = leadsHistoryRepository.deleteByLeadsId(leadsId);
//
//        //删除线索
//        leadsRepository.delete(leads);
        leads.forEach(e->{
            e.setDeleted(true);
        });

        leadsRepository.saveAll(leads);

        return 1;
    }

    private  ChildrenPO getChildrenPO(ChildMemberPo po1, Leads leads, StaffDTO modifyStaff) {
        ChildrenPO po=new ChildrenPO();
        po.setName(leads.getChildName());
        po.setNickName(leads.getNickName());
        po.setIdCard(leads.getIdCard());
        po.setChildBigName(leads.getChildName());
        po.setChildNickName(leads.getNickName());
        po.setChildAge(po1.getChildAge());
        po.setStaffId(modifyStaff.getId());
        po.setCrmClienteleId(leads.getId());
        po.setImgUrl(leads.getAvatar());
        po.setBirthday(po1.getBirthday());
        if (po1.getGender()==null){
            po.setGender(2);
        }else {
            po.setGender(po1.getGender());
        }
        po.setAddress(po1.getAddress());
        po.setAreaId(modifyStaff.getAreaId());
        List<ParentUserPO> linkMans=new ArrayList<>();
        List<LeadsUser> list = leadsUserRepository.findByLeadsId(leads.getId());
        for (LeadsUser leadsUser:list){
            ParentUserPO userPO=new ParentUserPO();
            BeanUtils.copyProperties(leadsUser,userPO,"id");
            userPO.setName(leadsUser.getUserName());
            userPO.setPhone(leadsUser.getMobile());
            userPO.setDetailedAddress(leadsUser.getAddress());
            userPO.setRelation(leadsUser.getRelationship());
            userPO.setRemark(leadsUser.getRemarks());
            userPO.setBirthDay(leadsUser.getBirthDay());
            userPO.setType(leadsUser.getType());
            linkMans.add(userPO);
        }
        po.setLinkMans(linkMans);
        return po;
    }

    @Override
    public boolean checkFollowById(String leadsId) {
        List<LeadsHistory> list = leadsHistoryRepository.findByLeadsIdAndType(leadsId, OPERATE_FOLLOW);
        if (list.size() > 0)
            return true;
        return false;
    }
}
